package cn.byapps.video.vue.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * ApiController
 */
@Controller
public class ApiController {

    @RequestMapping("api/{api}")
    public void api(@PathVariable String api, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //file:/C:/Users/Dianel/Downloads/iva0512-uniapp-movie-master/uniapp-movie/vue-server/vue-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/
        // System.out.println(api);
        String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        
        // System.out.println(path);
        path = path.substring(6,path.indexOf("vue-0.0.1.jar"));
        // System.out.println(path);
        /* 允许跨域的主机地址 */
        resp.setHeader("Access-Control-Allow-Origin", "*");
        /* 允许跨域的请求方法GET, POST, HEAD 等 */
        resp.setHeader("Access-Control-Allow-Methods", "*");
        /* 重新预检验跨域的缓存时间 (s) */
        resp.setHeader("Access-Control-Max-Age", "3600");
        /* 允许跨域的请求头 */
        resp.setHeader("Access-Control-Allow-Headers", "*");
        /* 是否携带cookie */
        resp.setHeader("Access-Control-Allow-Credentials", "true");

        resp.setHeader("content-type", "application/json");
        resp.setCharacterEncoding("utf-8");
        //ClassPathResource classPathResource = new ClassPathResource("static/json/in_theater.json");
        //InputStream inputStream = classPathResource.getInputStream();
        InputStream inputStream = new FileInputStream(new File(path + api +".json"));
        OutputStream sos = resp.getOutputStream();
        byte[] bytes = new byte[1024 * 8];
        int len;
        while ((len = inputStream.read(bytes)) != -1) {
            sos.write(bytes, 0, len);
        }
        inputStream.close();
        sos.flush();
        sos.close();

    }

}